#include "pgmodel.h"
#include "Sington.h"


#include <QDebug>

PGModel *PGModel::instance()
{
    return Sington<PGModel>::getInstance();
}

PGModel::PGModel(QObject *parent) :
    QAbstractListModel(parent)
{
}

// 元素的个数，或者说是model的大小/长度
int PGModel::rowCount(const QModelIndex &parent) const
{
    // For list models only the root node (an invalid parent) should return the list's size. For all
    // other (valid) parents, rowCount() should return 0 so that it does not become a tree model.
    if (parent.isValid())
        return 0;

    return m_datas.size();
}

QVariant PGModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid())
        return QVariant();
    QVariant var;
    if (role == PGRoleName::PGNAME) {
        var = QVariant::fromValue(m_datas[index.row()]->m_name);
    } else if (role == PGRoleName::PGPAGE) {
        var = QVariant::fromValue(m_datas[index.row()]->m_page);
    }
    return var;
}

QHash<int, QByteArray> PGModel::roleNames() const
{
    QHash<int, QByteArray> roles {
        {PGRoleName::PGNAME, "pgName"},   // 枚举C++使用
        {PGRoleName::PGPAGE, "pgPage"}    // 字符串Qml端使用
    };

    return roles;
}

void PGModel::remove(int index)
{
    if (index < 0 || index >= m_datas.size()) {
        return;
    }
    beginRemoveRows(QModelIndex(), index, index);
    delete m_datas.at(index);
    m_datas.removeAt(index);
    endRemoveRows();
}

void PGModel::insert(const int index, PGModelData *data)
{
    if(index < 0 || index > m_datas.size()) {
        return;
    }
    beginInsertRows(QModelIndex(), index, index);
    m_datas.insert(index, data);
    endInsertRows();
    emit insertNewItem(index);
}

void PGModel::append(PGModelData *data)
{
    insert(m_datas.size(), data);
}

bool PGModel::contains(QString name) const
{
    for (auto it = m_datas.begin(); it != m_datas.end(); ++it) {
        if (name == it.i->t()->m_name) {
            return true;
        }
    }
    return false;
}

PGModelData *PGModel::getItem(const int index)
{
    return m_datas[index];
}

int PGModel::itemCount() const
{
    return m_datas.size();
}
